/**
 * 
 */
'use strict';
// 通过 require 引入依赖
var $ = require('jquery');
require('angular-ui-router');
require("jquery-validation");
require('./service');
require('./expense/expenseController');
require('./performance/performanceController');
require('./point/pointController');
require('./recruitment/recruitmentController');

require('./directive');

angular.module('myApp',[ 'ui.router','myApp.directive','myApp.service','myApp.expense','myApp.performance','myApp.point','myApp.recruitment'])
	.constant("myAppConfig", {
		prefix: "/"
	})
	.config(["$httpProvider", '$locationProvider', '$stateProvider', '$urlRouterProvider', "myAppConfig",'$logProvider',
		function($httpProvider, $locationProvider, $stateProvider, $urlRouterProvider, myAppConfig,$logProvider) {
		
		$logProvider.debugEnabled(true);
		
		$urlRouterProvider.otherwise('/menu/point');

	    $stateProvider
	    	// 菜单
	        .state('menu', {
	            url: '/menu',
	            templateUrl: myAppConfig.prefix + 'app/menu.html'
	        })
	    	// 主页 - 我的积分
	        .state('menu.point', {
	            url: '/point',
	            templateUrl: myAppConfig.prefix + 'app/point/views/user.html',
	            controller : 'pointController'
	        })
	        // 我的业绩
	        .state('menu.performance', {
	            url: '/performance',
	            templateUrl: myAppConfig.prefix + 'app/performance/views/user_kpi.html',
	            controller : 'performanceController'
	        })
	        .state('performanceReward', {
	            url: '/reward',
	            templateUrl: myAppConfig.prefix + 'app/performance/views/user_kpi_reward.html',
	            controller : 'performanceController'
	        })
	        // 我的报销
	        .state('menu.expense', {
	        	url: '/expense',
	        	templateUrl: myAppConfig.prefix + 'app/expense/views/user_ea.html',
	        	controller : 'expenseController'
	        })
	        // 我的下线
	        .state('menu.recruitment', {
	        	url: '/recruitment',
	        	templateUrl: myAppConfig.prefix + 'app/recruitment/views/user_mr.html',
	        	controller : 'recruitmentController'
	        })
			.state('coopIntegral', {
	        	url: '/coopIntegral',
	        	templateUrl: myAppConfig.prefix + 'app/recruitment/views/user_coopIntegral.html',
	        	controller : 'recruitmentController'
	        })
	        .state('recruitmentSecond', {
	        	url: '/second/:custId/:custName',
	        	templateUrl: myAppConfig.prefix + 'app/recruitment/views/user_mr_2.html',
	        	controller : 'recruitmentController'
	        })
	        .state('recruitmentThird', {
	        	url: '/third/:custId/:custName',
	        	templateUrl: myAppConfig.prefix + 'app/recruitment/views/user_mr_3.html',
	        	controller : 'recruitmentController'
	        })
	      
	        // 增加angular $http请求头
	        /*$httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
	        */
	        $httpProvider.interceptors.push(['$injector', function ($injector) {
	        	return $injector.get('httpInterceptor');
	        }]);
		
	}])
	.controller('menuController',["$scope","$http","$location",  function($scope,$http,$location){
		
		$scope.initSelectedMenu = function(event){
			var cookieArray = document.cookie.split("; ");
		    for(var i=0;i < cookieArray.length; i++){
		        var aCrumb = cookieArray[i].split("=");
		        if ("menuId" == aCrumb[0]){
		        	var _currEleA = $("#"+aCrumb[1]);
		        	var _currEleLi = _currEleA.parent();
					_currEleLi.siblings().removeClass("active");
					_currEleLi.siblings().children().removeClass("selected");
					_currEleLi.addClass("active");
					_currEleA.addClass("selected");
		        }
		    }
		}
		
	}])
	// angular http请求拦截器
	.factory('httpInterceptor', [ '$q', '$injector',function($q, $injector) {
	    var httpInterceptor = { 
	      'responseError' : function(response) {
			// session过期 权限认证失败 登出页面
			window.location.href = "/logout";
			return $q.reject(response); 
	      }, 
	      'response' : function(response) {
	        return response; 
	      }, 
	      'request' : function(config) { 
	        return config; 
	      }, 
	      'requestError' : function(config){ 
	        return $q.reject(config); 
	      } 
	    } 
	  return httpInterceptor; 
	}])
	.run(['$rootScope', '$state', '$stateParams','$log',
		function ($rootScope,   $state,   $stateParams,$log) {
			
			$rootScope.$state = $state;
			$rootScope.$stateParams = $stateParams;
			
			function deleteCookie(name) {
		        var date = new Date();
		        date.setTime(date.getTime() - 10000); //删除一个cookie，就是将其过期时间设定为一个过去的时间
		        document.cookie = name + "=删除" + "; expires=" + date.toUTCString();
		    }
			
			$rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){
				// 菜单选中
				var menuArray = ['point','expense','performance','recruitment'];
				var fromStateName = fromState.name.split(".")[1];
				var toStateName = toState.name.split(".")[1];
				console.log(fromStateName + "->>" + toStateName);
				if(menuArray.indexOf(fromStateName) == -1 && menuArray.indexOf(toStateName) == -1){return;}
				deleteCookie("menuId");
				document.cookie =  "menuId=" + toStateName; //菜单加入缓存
				if(toStateName != undefined){
					var _currEleA = $("#" + toStateName);
				}else{
					var _currEleA = $("#" + fromStateName);
				}
				var _currEleLi = _currEleA.parent();
				_currEleLi.siblings().removeClass("active");
				_currEleLi.siblings().children().removeClass("selected");
				_currEleLi.addClass("active");
				_currEleA.addClass("selected");
				
				var hiddenMenuId = $("#hiddenMenuId").val();
				if(hiddenMenuId){
					$state.go('menu.' + hiddenMenuId);
					$("#hiddenMenuId").remove();
				}
				/*$log.debug('event', event);
				$log.debug('toState', toState);
				$log.debug('toParams', toParams);
				$log.debug('fromState', fromState);
				$log.debug('fromParams', fromParams);*/
			});

			$rootScope.$on('$stateNotFound', function(event, unfoundState, fromState, fromParams){
				$log.error('The request state was not found: ' + unfoundState);
			});

			$rootScope.$on('$stateChangeError', function(event, toState, toParams, fromState, fromParams, error){
				$log.error('An error occurred while changing states: ' + error);
			});
	    }
	]);